package com.mjfeed.interceptor;

import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mjfeed.entity.Admin;
import com.mjfeed.entity.AdminLog;
import com.mjfeed.service.AdminLogService;
import com.mjfeed.service.AdminService;

/**
 * @description 管理日志
 * @author zhaominglei
 * @date 2014年10月25日
 */
public class AdminLogInterceptor extends HandlerInterceptorAdapter {

	@Resource(name = "adminService")
	private AdminService adminService;
	@Resource(name = "adminLogService")
	private AdminLogService adminLogService;
	
	@SuppressWarnings("unchecked")
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		AdminLog adminLog = new AdminLog();
		String ip = getRemoteIpAddr(request);
		String url = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
		StringBuilder sb = new StringBuilder();
		Enumeration<String> headNames = request.getHeaderNames();
		while (headNames.hasMoreElements()) {
			String headName = (String) headNames.nextElement();
			String headValue = request.getHeader(headName);
			sb.append(headName).append(":").append(headValue).append(" ");
		}
		Admin admin = adminService.getCurrent();
		adminLog.setIp(ip);
		adminLog.setUrl(url);
		adminLog.setHttphead(sb.toString());
		adminLog.setOperator(admin);
		adminLogService.save(adminLog);
	}
	
	/**
	 * 获取访问端IP
	 * @return
	 */
	public String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
